<template>
  <div>
    <div class="w-1376">
      <header-search
        :select-value="searchSelectValue"
        placeholder="请输入模型库名称"
        :options="headerSearchSelectOptions"
        @onSearch="onSearch"
      />
    </div>
    <div class="main-content">
      <div>
        <div class="card-content">
          <div v-for="(item, index) in publicCardData" :key="index" class="card">
            <!-- 数量{{ index }} -->
            <model-base-card :data="item" @onClick="handleModelCard(item.id as string)" />
          </div>
        </div>
        <my-infinite-loading :empty="publicCardData?.length === 0" img-margin-top="120px" :identifier="identifier" @infinite="loadData" />
      </div>

      <a-affix :offset-top="120" :offset-left="40">
        <div ref="filterRef" class="screen-span">
          <div class="span-header">
            <div class="span-header-text">筛选标签</div>
            <a-button type="link" class="reset-button" @click="restSpan">重置</a-button>
          </div>

          <div class="span-header-line"></div>

          <div class="span-button my-scrollbar">
            <div
              v-for="(item, index) in spanButtonList"
              :key="index"
              class="span-box"
              :title="item.labelName + ' ' + item.count"
              :class="{ 'select-box': isSelected(item.labelId as string) }"
              @click="handleSpan(item as DictionaryType)"
            >
              <div class="span-text">{{ item.labelName }}</div>
              <div class="span-number">{{ item.count }}</div>
            </div>
          </div>
        </div>
      </a-affix>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute } from 'vue-router'

  import HeaderSearch, { HeaderSearchEvents } from '@/components/HeaderSearch/index.vue'
  import ModelBaseCard, { ModelCardData } from '@/components/ModelBaseCard/index.vue'
  import { modelLibraryApi } from '@/services/api'

  import { DictionaryType, PublicPageForm, TaskStatus } from '../types'
  import { headerSearchSelectOptions } from './options'

  const route = useRoute()

  const pageForm = ref<PublicPageForm>({
    modelName: '',
    labelIds: '',
    columns: 'createTime',
    order: 'desc',
    offset: 1,
    limit: 24
  })
  const identifier = ref<number>(1)
  const spanButtonList = ref<TaskStatus[]>([])
  const isClearList = ref<boolean>(false)
  //获取所有公共模块所用标签的信息
  const { runAsync: getAnchorData } = useRequest<ResponseData<DictionaryType[]>>(modelLibraryApi.labelInfo, {
    onSuccess: ({ data }) => {
      console.log(data, 'getAnchorData')
      spanButtonList.value = [...data]
    }
  })
  const publicCardData = ref<ModelCardData[]>([])
  const handleModelCard = (id: string) => {
    let url = `/model-base/list/public-model/public-model-datail/${id}?prePagePath=${route.path}&prePageName=公开模型`
    window.open(url, '_blank')
  }

  const loadData = async ($state: any) => {
    try {
      const {
        data: { records }
      } = await modelLibraryApi.commonModelList(pageForm.value)

      if (records.length < pageForm.value.limit) {
        $state.complete()
      } else {
        pageForm.value.offset++
        $state.loaded()
      }
      if (isClearList.value) {
        publicCardData.value = [...records]
        isClearList.value = false
      } else {
        publicCardData.value?.push(...records)
      }
    } catch (error) {
      $state.error()
    }
  }
  // 当前选中的标签
  const selectedItems = ref<string[]>([])

  const isSelected = (labelId: string) => {
    return selectedItems.value.includes(labelId)
  }

  const handleSpan = (item: DictionaryType) => {
    console.log(item, 'handleSpan')
    const index = selectedItems.value.indexOf(item.labelId)
    isClearList.value = true
    if (index === -1) {
      selectedItems.value.push(item.labelId)
    } else {
      selectedItems.value.splice(index, 1)
    }
    console.log(selectedItems.value, 'selectedItems')
    publicCardData.value = []
    pageForm.value.labelIds = [...selectedItems.value].toString()
    pageForm.value.offset = 1
    window.scrollTo({
      top: 0
    })
    identifier.value = new Date().getTime()
  }

  // 重置 --- 清除
  const restSpan = () => {
    isClearList.value = true
    selectedItems.value = []
    publicCardData.value = []
    pageForm.value.labelIds = [...selectedItems.value].toString()
    pageForm.value.offset = 1
    window.scrollTo({
      top: 0
    })
    identifier.value = new Date().getTime()
  }

  /* headerSearch组件搜索----------------------------------------------------------------------- */
  const searchSelectValue = ref('createTime--desc')
  const onSearch = (data: HeaderSearchEvents) => {
    const columns = data.selectValue.split('--')[0] || ''
    const order = data.selectValue.split('--')[1]! as 'asc' | 'desc'

    Object.assign(pageForm.value, {
      offset: 1,
      modelName: data.inputValue,
      columns,
      order
    })

    isClearList.value = true
    publicCardData.value = []
    identifier.value = new Date().getTime()
  }
  /* ------------------------------------------------------------------------------------------- */

  const filterRef = ref<null | HTMLElement>(null)

  // 监听页面滚动
  getAnchorData()
</script>
<style lang="less" scoped>
  .card-content {
    display: grid;
    width: 976px;
    gap: 20px;
    row-gap: 24px;
    grid-template-columns: repeat(auto-fill, minmax(312px, 1fr));
  }

  .main-content {
    display: flex;
    // gap: 0;
    justify-content: space-between;
  }

  .screen-span {
    position: static;
    display: flex;
    align-items: flex-start;
    padding: 16px 0;
    width: 360px;
    min-height: 400px;
    max-height: 642px;
    background: @background5;
    border: 1px solid @border1;
    border-radius: 10px;
    flex-direction: column;

    .span-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      // width: 100%;
      padding: 0 24px;
      margin-bottom: 12px;
      width: 100%;

      .span-header-text {
        color: @text01;
        .font14b();
      }

      .reset-button {
        height: 22px;
      }
    }

    .span-header-line {
      margin: 0 auto;
      width: calc(100% - 48px);
      height: 1px;
      border: 1px solid #e8e8eb;
    }

    .span-button {
      display: flex;
      align-items: flex-start;
      overflow-y: auto;
      // margin-right: 12px;
      padding: 0 24px;
      padding-right: 11px;
      margin-top: 24px;
      max-height: 537px;
      align-content: flex-start;
      gap: 8px;
      align-self: stretch;
      flex-wrap: wrap;
    }
  }

  .span-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 12px;
    max-width: 56%;
    color: rgba(21, 23, 27, 0.95);
    background: #fff;
    border: 1px solid @border1;
    border-radius: 100px;
    gap: 6px;
    .font14();

    .span-text {
      overflow: hidden;
      // max-width: 60px;
      max-width: 88%;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
    }

    .span-number {
      overflow: hidden;
      max-width: 24px;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
    }
  }

  .select-box {
    color: #fff;
    background: #0d4cca;
  }

  .infinite-box {
    display: flex;
    justify-content: center;
    width: 1040px;
  }
</style>
